<template>
  <div class="setrole">
    <el-dialog :title="'为【' + username + '】分配权限'" :visible="showRole">
      <el-tree
        :props="{ label: 'name' }"
        :data="list"
        ref="mytree"
        default-expand-all
        show-checkbox
        node-key="id"
        :check-strictly="true"
      >
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="pancel">取 消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//获取所有的权限列表
import { getAllPerApi } from '@/api/permission'
import { getRoleDetailApi, assignRoleApi } from '@/api/setting'
export default {
  name: 'setrole',
  //username：权限名称
  //showRole:控制面板的显示与隐藏
  props: ['showRole', 'username'],
  data () {
    return {
      //所有权限的数据源
      list: [],
      //当前角色的权限列表
      thisRole: [],
      //当前选中权限的id
      id: ''
    }
  },
  methods: {
    //获取角色详情
    async getRoleDetail (id) {
      this.id = id
      const res = await getRoleDetailApi(id)
      this.thisRole = res.data.permIds
      // 动态将权限对应的节点选中
      this.$refs.mytree.setCheckedKeys(this.thisRole)
    },
    //获取所有的权限列表
    async getAllPerAll () {
      const res = await getAllPerApi()
      this.list = this.trunData(res.data, '0')
    },
    //将并列结构转成树状结构
    trunData (arr, pid) {
      const newArr = []
      arr.forEach(item => {
        if (item.pid === pid) {
          const children = this.trunData(arr, item.id)
          if (children.length > 0) {
            item.children = children
          }
          newArr.push(item)
        }
      })
      return newArr
    },
    //点击取消按钮,关闭面板
    pancel () {
      this.$emit('update:showRole', false)
    },
    //点击确定按钮
    async submit () {
      //得到当前选中的权限
      const str = this.$refs.mytree.getCheckedKeys()
      //提交数据到服务器
      const res = await assignRoleApi({
        id: this.id,
        permIds: str
      })
      //关闭面板
       this.$emit('update:showRole', false)
      //提示修改成功
      this.$message.success('分配权限成功')
    }
  },
  created () {
    this.getAllPerAll()
  }
}
</script>

<style></style>
